<template>
  <div class="app-container">
    <div class="container-box" style="display: flex;flex-direction: row;">
      <div id="chart" style="width: 100%;height: 400px" />
    </div>

    <div class="container-box">
      <div class="table-title text-primary"> 经费分配记录</div>
      <div class="filter-container">
        <el-input v-model="listQuery.title" placeholder="查询内容" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
        <el-button v-waves class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-search" @click="handleFilter">
          搜索
        </el-button>
        <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
          分配经费
        </el-button>
        <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">
          下载数据
        </el-button>
      </div>

      <el-table
        v-loading="listLoading"
        :data="list"
        border
        fit
        highlight-current-row
        style="width: 100%;"
        @sort-change="sortChange"
      >
        <el-table-column label="#编号" prop="id" sortable="custom" align="center" width="100" :class-name="getSortClass('id')">
          <template slot-scope="{row}">
            <span>{{ row.id }}</span>
          </template>
        </el-table-column>
        <el-table-column label="社团" width="110px" align="center">
          <template slot-scope="{row}">
            <span>{{ row.orgName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="用途" min-width="110px" align="center">
          <template slot-scope="{row}">
            <span>{{ row.reason }}</span>
          </template>
        </el-table-column>
        <el-table-column label="起效时间" width="150px" align="center">
          <template slot-scope="{row}">
            <span>{{ row.stDate| parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="无效时间" width="150px" align="center">
          <template slot-scope="{row}">
            <span>{{ row.endDate| parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="金额" width="110px" align="center">
          <template slot-scope="{row}">
            <span>{{ row.total }}</span>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
    </div>

    <el-dialog title="分配金额" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="100px" style="width: 400px; margin-left:50px;">
        <el-form-item label="社团">
          <el-select v-model="temp.oid" class="filter-item" placeholder="Please select">
            <el-option v-for="item in orgOptions" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="用途">
          <el-input v-model="temp.reason" />
        </el-form-item>
        <el-form-item label="金额">
          <el-input v-model="temp.total" />
        </el-form-item>
        <el-form-item label="生效时间">
          <el-date-picker
            v-model="temp.dateSpan"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="createData">
          确定
        </el-button>
      </div>
    </el-dialog>
    <el-dialog title="删除确认" :visible.sync="modifyDialogFormVisible" style="width: 450px;margin: 0 auto">
      <div ref="dataForm" style="width: 100%;" class="text-danger">
        <span><i class="el-icon-warning-outline" /></span>
        删除数据将无法恢复
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="modifyDialogFormVisible = false">
          取消
        </el-button>
        <el-button type="danger" @click="updateData">
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import echarts from 'echarts'
import { fetchExpDisList, fetchTotalDistributionChartData, updateExpUse, addExpDis } from '@/api/expenditure'
import { fetchOrgNames } from '@/api/com'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination

const calendarTypeOptions = [
  { key: 'username', display_name: '报销人姓名' },
  { key: 'orgName', display_name: '社团' }
]
const calendarStatusOptions = [
  { key: '0', display_name: '拒绝' },
  { key: '1', display_name: '申请中' },
  { key: '2', display_name: '接受' },
  { key: '3', display_name: '全选' }
]
const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})

export default {
  name: 'ExpDisDetail',
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        '接受': 'success',
        '拒绝': 'danger',
        '申请中': 'info'
      }
      return statusMap[status]
    },
    typeFilter(type) {
      return calendarTypeKeyValue[type]
    }
  },
  data() {
    var validateTotal = (rule, value, callback) => {
      setTimeout(() => {
        var reg = /^\d+(?=\.{0,1}\d+$|$)/
        if (!reg.test(value)) { callback(new Error('请输入数字值')) }
      }, 200)
    }
    return {
      chart: null,
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        oid: null,
        type: '',
        title: '',
        page: 1,
        limit: 10,
        status: '申请中'
      },
      importanceOptions: [1, 2, 3],
      orgOptions: null,
      calendarTypeOptions,
      calendarStatusOptions,
      sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
      genderOptions: ['男', '女'],
      statusOptions: ['在职', '离队', '退役'],
      positionOptions: ['社长', '部长', '干事'],
      showReviewer: false,
      temp: {
        name: '',
        userId: '',
        total: '',
        org: '',
        class: ''
      },
      dialogFormVisible: false,
      modifyDialogFormVisible: false,
      deleteTemp: -1,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '新建'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        total: { validator: validateTotal, trigger: 'blur' }
      },
      downloadLoading: false,
      chartData: {
        title: {
          text: '经费分配情况',
          subtext: '',
          left: 'center'
        },
        tooltip: {
          trigger: 'item'
        },
        legend: {
          orient: 'vertical',
          left: 'left'
        },
        series: [
          {
            name: '访问来源',
            type: 'pie',
            radius: '50%',
            data: [
              { value: 735, name: '学生会' },
              { value: 580, name: '计算机服务队' },
              { value: 484, name: '软件俱乐部' },
              { value: 484, name: '自行车协会' },
              { value: 484, name: '动漫社' },
              { value: 300, name: '青志' },
              { value: 1048, name: '未分配' }
            ],
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  mounted() {
    this.initChart()
    fetchOrgNames().then(res => { this.orgOptions = res.data.items })
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    getList() {
      this.listLoading = true
      fetchExpDisList(this.listQuery).then(res => {
        this.list = res.data.items
        this.total = res.data.total
        for (const i in this.list) {
          this.list[i].stDate = new Date(this.list[i].stDate).getTime()
          this.list[i].endDate = new Date(this.list[i].endDate).getTime()
        }
        setTimeout(() => {
          this.listLoading = false
        }, 400)
      })
    },
    toDetail(id) {
      this.$router.push({ path: '/expenditure/detail/' + id })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        oid: null,
        reason: '',
        total: null,
        dateSpan: null
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      const form = Object.assign({}, this.temp)
      form['stDate'] = parseTime(form.dateSpan[0], '{y}-{m}-{d} {h}:{i}:{s}')
      form['endDate'] = parseTime(form.dateSpan[1], '{y}-{m}-{d} {h}:{i}:{s}')
      addExpDis(form).then(
        res => {
          if (res.status === 200) {
            this.getList()
            this.initChart()
            this.$notify({
              title: 'Success',
              message: 'add Successfully',
              type: 'success',
              duration: 500
            })
          }
        }
      )
      this.dialogFormVisible = false
      console.log(this.temp)
    },
    handleModify(row, status) {
      const temp = Object.assign({}, row)
      temp.status = '拒绝'
      temp['uid'] = temp.user.id
      temp['oid'] = temp.org.id
      temp.total = String(temp.total)
      temp.status = status
      temp.date = parseTime(temp.date, '{y}-{m}-{d} {h}:{i}:{s}')
      this.modifyDialogFormVisible = true
      this.temp = temp
    },
    updateData() {
      this.modifyDialogFormVisible = false
      updateExpUse(this.temp).then(
        res => {
          if (res.status === 200) {
            this.getList()
            this.initChart()
            this.$notify({
              title: 'Success',
              message: 'add Successfully',
              type: 'success',
              duration: 500
            })
          }
        }
      )
    },
    deleteData() {
      this.$notify({
        title: 'Success',
        message: 'Delete Successfully',
        type: 'success',
        duration: 2000
      })
      this.list.splice(this.deleteTemp, 1)
      this.deleteTemp = -1
      this.modifyDialogFormVisible = false
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['学号', '姓名', '性别', '社团', '职位', '状态', '简介']
        const filterVal = ['id', 'name', 'gender', 'org', 'position', 'status', 'intro']
        const data = this.formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: '社团成员表（总）'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    },
    initChart() {
      fetchTotalDistributionChartData().then(
        res => {
          this.chartData.series[0].data = res.data.items
          this.chart = echarts.init(document.getElementById('chart'))
          this.chart.setOption(this.chartData)
        }
      )
    }
  }
}
</script>
<style lang="scss" scoped>
.container-box{
  margin: 20px;
  padding: 30px;
  border-radius: 5px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);
}
.table-title{
  font-weight: bolder;
  font-size: 25px;
  margin-bottom: 20px;
}
.form-item{
  display: flex;
  flex-direction: row;
  font-size: 20px;
  margin: 5px;
}
.form-label{
  font-weight: bold;
}
.form-value{
  color: #7d7d7f;
}
</style>
